
const preprocessor = require("./preprocess/preprocess")
const { transUniTemplateToWeb, getEasycomFromAst, genImportFromEasycomp, parseSfc } = require('./preprocess/utils');
/**
 * 将vue单文件 去除条件编译的不可达代码、导入easycom组件
 */
const getTransVueCode = (code, targetPlatform = "pc") => {
    const context = { H5: targetPlatform !== "mobile" }
    const parseRes = parseSfc(code);
    let newCode = ""
    //template
    const templateContent = parseRes.template.content;
    let newTemplateContent = preprocessor.preprocess(templateContent, context, { type: "html" })
    newTemplateContent = transUniTemplateToWeb(newTemplateContent);
    const easycomList = getEasycomFromAst(parseRes.template.ast);
    newCode += (newTemplateContent ? `<template>${newTemplateContent}</template>\n` : "");
    //script
    const scriptContent = parseRes.script.content;
    let newScriptContent = preprocessor.preprocess(scriptContent, context, { type: "js" })

    newCode += (newScriptContent ? `<script${parseRes.script.attrs.lang === "ts" ? " lang=ts" : ""}>${newScriptContent}</script>\n` : "")
    //scriptSetup
    const scriptSetupContent = parseRes.scriptSetup.content;
    let newScriptSetupContent = preprocessor.preprocess(scriptSetupContent, context, { type: "js" })
    newScriptSetupContent = genImportFromEasycomp(easycomList, newScriptSetupContent, targetPlatform);
    newCode += (newScriptSetupContent ? `<script setup${parseRes.script.attrs.hasOwnProperty('name') ? ` name=${parseRes.script.attrs.name}` : ""}${parseRes.script.attrs.hasOwnProperty('lang') ? ` lang=${parseRes.script.attrs.lang}` : ""}>${newScriptSetupContent}</script>\n` : "")
    //styles
    parseRes.styles.forEach(el => {
        //console.log(el)
        const styleContent = el.content;
        let newStyleContent = preprocessor.preprocess(styleContent, context, { type: "js" });
        newStyleContent = `@import "@gd-accbuild-core/theme-chalk/pc-admin/index.module.scss";\n` + newStyleContent
        newCode += (newStyleContent ? `<style lang="scss" ${el.attrs.scoped ? " scoped" : ""}${el.attrs.module ? (el.attrs.module == true ? " module" : ` module="${el.attrs.module}"`) : ""}>${newStyleContent}</style>\n` : "")
    })
    console.log(newCode)
    return newCode
}

//preprocessor.preprocessFileSync("./test.vue","./test-2.vue",{UNI_PLATFORM:"H5"})

/* optimizeDeps: {
    include: ['esm-dep > cjs-dep'],
  }, */
export const gdUniTransform = ({targetPlatform="pc"}) => {
    const vueRE = /\.vue$/;
    return {
        name: 'gd-uni-transform',
        transform(src, id) {
            if (id.toLowerCase().indexOf('gd-accbuild-core/components/gd-accbuild-ui') !== -1 && vueRE.test(id)) {
                return {
                    code: getTransVueCode(src,targetPlatform),
                    map: null // 如果可行将提供 source map
                }
            }
        }
    }
}